package network.server.handler.StoreHandler;

import common.model.Entity.StoreEntity.OrderItem;
import module.StoreService.OrderItemService;
import module.StoreService.Impl.OrderItemServiceImpl;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * {@code OrderItemHandler} 是订单项相关请求的处理器，实现了 {@link RequestHandler} 接口。
 * <p>
 * 功能概述：
 * <ul>
 *     <li>接收并解析客户端请求</li>
 *     <li>调用 {@link OrderItemService} 执行订单项的增删改查逻辑</li>
 *     <li>支持单个与批量订单项操作（JSON 或 Map 格式解析）</li>
 *     <li>返回统一的 {@link Response} 封装结果</li>
 * </ul>
 * <p>
 * 支持的操作：
 * <ul>
 *     <li>{@code getOrderItemById} - 根据订单项 ID 获取订单项</li>
 *     <li>{@code getOrderItemsByOrderId} - 根据订单 ID 获取订单项列表</li>
 *     <li>{@code getAllOrderItems} - 获取所有订单项</li>
 *     <li>{@code createOrderItem} - 创建单个订单项</li>
 *     <li>{@code updateOrderItem} - 更新订单项</li>
 *     <li>{@code deleteOrderItem} - 删除订单项</li>
 *     <li>{@code deleteOrderItemsByOrderId} - 根据订单 ID 删除订单项</li>
 *     <li>{@code getOrderItemCount} - 获取订单项总数</li>
 *     <li>{@code calculateOrderTotal} - 计算订单总金额</li>
 *     <li>{@code createOrderItems} - 批量创建订单项</li>
 * </ul>
 */
public class OrderItemHandler implements RequestHandler {
    private final OrderItemService orderItemService;

    /**
     * 构造函数，初始化时使用 {@link OrderItemServiceImpl#getInstance()} 获取单例服务对象。
     */
    public OrderItemHandler() {
        this.orderItemService = OrderItemServiceImpl.getInstance();
    }

    /**
     * 处理客户端请求，根据 action 映射到具体的订单项操作方法。
     *
     * @param req 请求对象，包含 action 和参数
     * @return 响应对象，包含执行结果或错误信息
     */
    @Override
    public Response<?> handle(Request req) {
        String action = req.getAction();
        String methodName = action.substring(action.indexOf('.') + 1);
        Map<String, Object> params = req.getParams();

        try {
            switch (methodName) {
                case "getOrderItemById":
                    return handleGetOrderItemById(params);
                case "getOrderItemsByOrderId":
                    return handleGetOrderItemsByOrderId(params);
                case "getAllOrderItems":
                    return orderItemService.getAllOrderItems();
                case "createOrderItem":
                    return handleCreateOrderItem(params);
                case "updateOrderItem":
                    return handleUpdateOrderItem(params);
                case "deleteOrderItem":
                    return handleDeleteOrderItem(params);
                case "deleteOrderItemsByOrderId":
                    return handleDeleteOrderItemsByOrderId(params);
                case "getOrderItemCount":
                    return orderItemService.getOrderItemCount();
                case "calculateOrderTotal":
                    return handleCalculateOrderTotal(params);
                case "createOrderItems":
                    return handleCreateOrderItems(params);
                default:
                    return Response.error("未知操作: " + methodName);
            }
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            return Response.error("处理请求时发生错误: " + e.getMessage());
        }
    }

    /**
     * 根据 ID 获取订单项。
     *
     * @param params 请求参数，必须包含 {@code id}
     * @return 订单项对象或错误信息
     */
    private Response<?> handleGetOrderItemById(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return orderItemService.getOrderItemById(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 根据订单 ID 获取订单项列表。
     *
     * @param params 请求参数，必须包含 {@code orderId}
     * @return 订单项列表或错误信息
     */
    private Response<?> handleGetOrderItemsByOrderId(Map<String, Object> params) {
        if (!params.containsKey("orderId")) {
            return Response.error("缺少必要参数: orderId");
        }

        try {
            Object orderIdObj = params.get("orderId");
            if (orderIdObj == null) {
                return Response.error("orderId参数不能为null");
            }
            long orderId = Long.parseLong(orderIdObj.toString());
            return orderItemService.getOrderItemsByOrderId(orderId);
        } catch (NumberFormatException e) {
            return Response.error("orderId参数格式错误");
        }
    }

    /**
     * 创建订单项。
     *
     * @param params 请求参数，必须包含 {@code orderId}, {@code productId}, {@code quantity}, {@code price}
     * @return 创建结果
     */
    private Response<?> handleCreateOrderItem(Map<String, Object> params) {
        if (!params.containsKey("orderId") || !params.containsKey("productId") ||
                !params.containsKey("quantity") || !params.containsKey("price")) {
            return Response.error("缺少必要参数: orderId, productId, quantity, price");
        }

        try {
            OrderItem orderItem = new OrderItem();

            Object orderIdObj = params.get("orderId");
            if (orderIdObj == null) {
                return Response.error("orderId参数不能为null");
            }
            orderItem.setOrderId(Long.parseLong(orderIdObj.toString()));

            Object productIdObj = params.get("productId");
            if (productIdObj == null) {
                return Response.error("productId参数不能为null");
            }
            orderItem.setProductId(Long.parseLong(productIdObj.toString()));

            Object quantityObj = params.get("quantity");
            if (quantityObj == null) {
                return Response.error("quantity参数不能为null");
            }
            orderItem.setQuantity(Integer.parseInt(quantityObj.toString()));

            Object priceObj = params.get("price");
            if (priceObj == null) {
                return Response.error("price参数不能为null");
            }
            orderItem.setPrice(Double.parseDouble(priceObj.toString()));

            return orderItemService.createOrderItem(orderItem);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误");
        }
    }

    /**
     * 更新订单项。
     *
     * @param params 请求参数，必须包含 {@code id}，可选 {@code quantity}, {@code price}
     * @return 更新结果
     */
    private Response<?> handleUpdateOrderItem(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());

            Response<Optional<OrderItem>> response = orderItemService.getOrderItemById(id);
            if (!response.isSuccess() || response.getData().isEmpty()) {
                return Response.error("未找到指定订单项");
            }

            OrderItem orderItem = response.getData().get();

            if (params.containsKey("quantity")) {
                Object quantityObj = params.get("quantity");
                if (quantityObj != null) {
                    orderItem.setQuantity(Integer.parseInt(quantityObj.toString()));
                }
            }

            if (params.containsKey("price")) {
                Object priceObj = params.get("price");
                if (priceObj != null) {
                    orderItem.setPrice(Double.parseDouble(priceObj.toString()));
                }
            }

            return orderItemService.updateOrderItem(orderItem);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误");
        }
    }

    /**
     * 删除订单项。
     *
     * @param params 请求参数，必须包含 {@code id}
     * @return 删除结果
     */
    private Response<?> handleDeleteOrderItem(Map<String, Object> params) {
        if (!params.containsKey("id")) {
            return Response.error("缺少必要参数: id");
        }

        try {
            Object idObj = params.get("id");
            if (idObj == null) {
                return Response.error("id参数不能为null");
            }
            long id = Long.parseLong(idObj.toString());
            return orderItemService.deleteOrderItem(id);
        } catch (NumberFormatException e) {
            return Response.error("id参数格式错误");
        }
    }

    /**
     * 根据订单 ID 删除订单项。
     *
     * @param params 请求参数，必须包含 {@code orderId}
     * @return 删除结果
     */
    private Response<?> handleDeleteOrderItemsByOrderId(Map<String, Object> params) {
        if (!params.containsKey("orderId")) {
            return Response.error("缺少必要参数: orderId");
        }

        try {
            Object orderIdObj = params.get("orderId");
            if (orderIdObj == null) {
                return Response.error("orderId参数不能为null");
            }
            long orderId = Long.parseLong(orderIdObj.toString());
            return orderItemService.deleteOrderItemsByOrderId(orderId);
        } catch (NumberFormatException e) {
            return Response.error("orderId参数格式错误");
        }
    }

    /**
     * 计算订单总金额。
     *
     * @param params 请求参数，必须包含 {@code orderId}
     * @return 总金额
     */
    private Response<?> handleCalculateOrderTotal(Map<String, Object> params) {
        if (!params.containsKey("orderId")) {
            return Response.error("缺少必要参数: orderId");
        }

        try {
            Object orderIdObj = params.get("orderId");
            if (orderIdObj == null) {
                return Response.error("orderId参数不能为null");
            }
            long orderId = Long.parseLong(orderIdObj.toString());
            return orderItemService.calculateOrderTotal(orderId);
        } catch (NumberFormatException e) {
            return Response.error("orderId参数格式错误");
        }
    }

    /**
     * 批量创建订单项 - 支持 JSON 字符串或 List<Map> 格式。
     *
     * @param params 请求参数，必须包含 {@code orderItems}
     * @return 创建结果
     */
    private Response<?> handleCreateOrderItems(Map<String, Object> params) {
        if (!params.containsKey("orderItems")) {
            return Response.error("缺少必要参数: orderItems");
        }

        try {
            Object orderItemsObj = params.get("orderItems");
            List<OrderItem> orderItems = new ArrayList<>();

            if (orderItemsObj instanceof String) {
                String orderItemsJson = (String) orderItemsObj;
                JSONArray jsonArray = JSON.parseArray(orderItemsJson);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    OrderItem orderItem = parseOrderItemFromJson(jsonObject);
                    if (orderItem.getOrderId() <= 0 || orderItem.getProductId() <= 0 ||
                            orderItem.getQuantity() <= 0 || orderItem.getPrice() < 0) {
                        return Response.error("订单项数据不完整或无效");
                    }
                    orderItems.add(orderItem);
                }
            } else if (orderItemsObj instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> orderItemsList = (List<Map<String, Object>>) orderItemsObj;
                for (Map<String, Object> itemMap : orderItemsList) {
                    OrderItem orderItem = parseOrderItemFromMap(itemMap);
                    if (orderItem.getOrderId() <= 0 || orderItem.getProductId() <= 0 ||
                            orderItem.getQuantity() <= 0 || orderItem.getPrice() < 0) {
                        return Response.error("订单项数据不完整或无效");
                    }
                    orderItems.add(orderItem);
                }
            } else {
                return Response.error("orderItems参数格式不正确");
            }

            if (orderItems.isEmpty()) {
                return Response.error("订单项列表为空");
            }

            return orderItemService.createOrderItems(orderItems);
        } catch (Exception e) {
            return Response.error("参数格式错误: " + e.getMessage());
        }
    }

    /**
     * 从 JSONObject 解析订单项。
     *
     * @param jsonObject JSON 对象
     * @return 订单项对象
     */
    private OrderItem parseOrderItemFromJson(JSONObject jsonObject) {
        OrderItem orderItem = new OrderItem();

        if (jsonObject.containsKey("order_id")) {
            orderItem.setOrderId(jsonObject.getLongValue("order_id"));
        } else if (jsonObject.containsKey("orderId")) {
            orderItem.setOrderId(jsonObject.getLongValue("orderId"));
        }

        if (jsonObject.containsKey("product_id")) {
            orderItem.setProductId(jsonObject.getLongValue("product_id"));
        } else if (jsonObject.containsKey("productId")) {
            orderItem.setProductId(jsonObject.getLongValue("productId"));
        }

        if (jsonObject.containsKey("quantity")) {
            orderItem.setQuantity(jsonObject.getIntValue("quantity"));
        }

        if (jsonObject.containsKey("price")) {
            orderItem.setPrice(jsonObject.getDoubleValue("price"));
        }

        return orderItem;
    }

    /**
     * 从 Map 解析订单项。
     *
     * @param itemMap 参数 Map
     * @return 订单项对象
     */
    private OrderItem parseOrderItemFromMap(Map<String, Object> itemMap) {
        OrderItem orderItem = new OrderItem();

        if (itemMap.containsKey("order_id")) {
            Object orderIdObj = itemMap.get("order_id");
            if (orderIdObj != null) {
                orderItem.setOrderId(Long.parseLong(orderIdObj.toString()));
            }
        } else if (itemMap.containsKey("orderId")) {
            Object orderIdObj = itemMap.get("orderId");
            if (orderIdObj != null) {
                orderItem.setOrderId(Long.parseLong(orderIdObj.toString()));
            }
        }

        if (itemMap.containsKey("product_id")) {
            Object productIdObj = itemMap.get("product_id");
            if (productIdObj != null) {
                orderItem.setProductId(Long.parseLong(productIdObj.toString()));
            }
        } else if (itemMap.containsKey("productId")) {
            Object productIdObj = itemMap.get("productId");
            if (productIdObj != null) {
                orderItem.setProductId(Long.parseLong(productIdObj.toString()));
            }
        }

        if (itemMap.containsKey("quantity")) {
            Object quantityObj = itemMap.get("quantity");
            if (quantityObj != null) {
                orderItem.setQuantity(Integer.parseInt(quantityObj.toString()));
            }
        }

        if (itemMap.containsKey("price")) {
            Object priceObj = itemMap.get("price");
            if (priceObj != null) {
                orderItem.setPrice(Double.parseDouble(priceObj.toString()));
            }
        }

        return orderItem;
    }
}
